# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: jaewon

import hashlib

from experimental.prophet.graph import graph
from experimental.prophet.ops.util import to_tuple


class _ScalarValueAggregator:
  def __init__(self, values, node_name):
    self._values = [graph.as_variable(v) for v in to_tuple(values)]
    self._colnames = [(v.name or v.instance_name) for v in self._values]
    self._node = graph.create_node('ScalarValueAggregator',
                                   self._values,
                                   name=node_name,
                                   attrs={'column_names': self._colnames})

  @property
  def values(self):
    return self._values

  @property
  def colnames(self):
    return self._colnames

  @property
  def instance(self):
    return self._node.outputs[0].instance.get_value_aggregator()

  def get_hash(self):
    graph_hash = self._node.graph.get_graph_hash()
    varnames = str({idx: v.instance_name for idx, v in enumerate(self._values)})
    colnames = str({idx: col for idx, col in enumerate(self._colnames)})
    base_str = str((graph_hash, varnames, colnames))
    return hashlib.sha256(base_str.encode('utf-8')).hexdigest()

  def dump(self, filepath, dump_pending_row=False):
    self.instance.dump(filepath, dump_pending_row=dump_pending_row)


def scalar_value_aggregator(values, node_name=None):
  return _ScalarValueAggregator(values, node_name=node_name)
